#include <catch2/catch_test_macros.hpp>
#include <iostream>
#include <sstream>
#include <string>
#include <unordered_map>

// 解析表单数据
std::unordered_map<std::string, std::string> parseFormData(const std::string& formData)
{
    std::unordered_map<std::string, std::string> data;

    std::istringstream iss(formData);
    std::string        line;
    while (std::getline(iss, line, '&'))
    {
        std::istringstream pairIss(line);
        std::string        key;
        std::string        value;
        if (std::getline(pairIss, key, '=') && std::getline(pairIss, value))
        {
            // 对 key 和 value 进行 URL 解码
            // ...

            data[key] = value;
        }
    }

    return data;
}

std::string urlDecode(const std::string& encoded)
{
    std::stringstream decoded;
    std::stringstream hexStream;

    for (std::size_t i = 0; i < encoded.length(); ++i)
    {
        if (encoded[i] == '%')
        {
            hexStream.str(encoded.substr(i + 1, 2));
            int hexValue = 0;
            hexStream >> std::hex >> hexValue;

            // 转换为 char 并追加到结果中
            decoded << static_cast<char>(hexValue);

            // 跳过已处理的两个字符
            i += 2;
        }
        else if (encoded[i] == '+')
        {
            // 将 '+' 替换为 ' '
            decoded << ' ';
        }
        else
        {
            // 直接追加其他字符
            decoded << encoded[i];
        }
    }

    return decoded.str();
}

TEST_CASE("Parse http post", "[http]")
{
    std::string formData = "param1=value1&param2=value2&param3=value3";

    std::unordered_map<std::string, std::string> data = parseFormData(formData);

    // 输出解析后的数据
    for (const auto& [key, value] : data)
    {
        std::cout << "Key: " << key << ", Value: " << value << std::endl;
    }

    std::string encoded = "Hello%20World%21%2B%25";
    std::string decoded = urlDecode(encoded);

    std::cout << "Encoded: " << encoded << std::endl;
    std::cout << "Decoded: " << decoded << std::endl;
    // REQUIRE(1 + 2 != 2);
}
